import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { Button, LoadPanel, Popup, SelectBox, TextBox } from 'devextreme-react';
import { DevPopup } from '~/public/cpas-ui';
import { useModel } from 'umi';
import { intl } from '@/utils';
import { draftList, draftSave, queryDraftTemplateIsExistByTemplateName } from './service';
import notify from 'devextreme/ui/notify';
import { message } from 'antd';

const SaveTemplate = React.forwardRef((props: any, ref: any) => {
    const { curPhaseData } = props;

    const { initialState } = useModel('@@initialState');
    const { dbname, zcbfid, sjxmbh } = initialState?.curPart as API.CurPart;

    const [visible, setVisible] = useState<boolean>(false);
    const [isShowGloablLoad, setIsShowGloablLoad] = useState<boolean>(false);
    const [visibleLogic, setVisibleLogic] = useState<boolean>(false);
    const diaParams = useRef<any>();
    const refsForm = useRef<any>();
    const SaveRef = useRef<any>();
    const [PaperValue, setPaperValue] = useState('')

    const [listData, setListData] = useState<any[]>([]);
    const [templateName, setTemplateName] = useState<string>('');

    const GetDataList = async () => {
        try {
            const r = await draftList();
            setListData(r.data)
        } catch (error) {
            console.log(error);
        }
    }

    useEffect(() => {
        if (visible) {
            GetDataList()
        }
    }, [visible])

    useImperativeHandle(ref, () => (
        {
            show: (params: any) => {
                diaParams.current = params;
                setVisible(true);
                setTemplateName('');
            }
        }
    ))

    const onSelectionChangeds = (e) => {
        setTemplateName(e.selectedItem.MBMC)
    }

    const onCancel = () => {
        setVisible(false);
    }

    const onOk = async () => {
        if (!templateName) {
            return notify("模板名称不能为空!", 'error', 3000);
        }
        const r = await queryDraftTemplateIsExistByTemplateName({
            templateName: templateName
        })
        if (r.data) {
            setVisibleLogic(true)
        } else {
            setIsShowGloablLoad(true);
            const rs = await draftSave({
                MBMC: templateName,
                dbname: dbname,
                zcbfid: zcbfid,
                sjxmbh: sjxmbh,
                DGND: curPhaseData
            })
            if (rs.success) {
                setVisible(false);
                GetDataList();
                notify("保存成功", 'success', 2000);
            }
            setIsShowGloablLoad(false);
        }
    }


    return (
        <>
            <Popup
                ref={ref}
                visible={visible}
                title='保存为底稿模板'
                width={500}
                height={200}
                {...props}
                onHiding={() => setVisible(false)}
            /* 这个不行,有时候点击确定按钮第一次不生效,要点击两次
             toolbarItems={[
                {
                    widget: 'dxButton',
                    toolbar: 'bottom',
                    location: 'after',
                    options: {
                        text: intl('pub.cancel', '取消'),
                        onClick: () => onCancel()
                    },
                },
                {
                    widget: 'dxButton',
                    toolbar: 'bottom',
                    location: 'after',
                    options: {
                        text: intl('pub.ok', '确定'),
                        type: 'default',
                        onClick: () => {
                            alert("OK")
                            onOk();
                        }
                    },
                },
            ]} */
            >
                <div
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        marginTop: 10,
                    }}
                >
                    <span style={{ marginRight: "10px" }}>
                        模板名称
                    </span>
                    {/* 改为输入框,不能用选择框 by csb 20230716 */}
                    <TextBox
                        width={390}
                        ref={refsForm}
                        defaultValue={listData && listData.length > 0 ? listData[0].MBMC : ""}
                        value={templateName}
                        placeholder='请输入模板名称'
                        onChange={(e) => {
                            setTemplateName(e.event?.currentTarget?.value);
                        }}
                    />
                    {/* <SelectBox
                        width={300}
                        ref={refsForm}
                        items={listData}
                        displayExpr='MBMC'
                        valueExpr='MBMC'
                        value={templateName}
                        searchEnabled={true}
                        acceptCustomValue={true}
                        placeholder='请输入模板名称'
                        displayValue={templateName}
                        onInput={(e: any) => {
                            const { event } = e;
                            // console.log(,'event.target.value-----');
                            setTemplateName(event.target.value)
                        }}
                        onCustomItemCreating={() => { }}
                        onSelectionChanged={onSelectionChangeds}
                    /> */}
                </div>
                <div style={{ textAlign: "right", marginTop: 40 }}>
                    <Button text="取消" onClick={() => onCancel()} />
                    <Button text="确定" onClick={() => onOk()} type="default" style={{ marginLeft: 30 }} />
                </div>
            </Popup>
            <DevPopup.Logic
                // ref={ref}
                shadingColor='rgba(0, 0, 0, 0)'
                width={400}
                height={200}
                visible={visibleLogic}
                title="询问"
                okText="是"
                cancelText="否"
                onOK={async () => {
                    setIsShowGloablLoad(true)
                    const r = await draftSave({
                        MBMC: templateName,
                        dbname: dbname,
                        zcbfid: zcbfid,
                        sjxmbh: sjxmbh,
                        DGND: curPhaseData
                    })
                    console.log(r, 'r-----------');
                    if (r.success) {
                        setIsShowGloablLoad(false)
                        notify("保存成功", 'success', 2000);
                        setVisible(false);
                    }
                    setVisibleLogic(false);
                }}
                onCancel={() => {
                    setVisibleLogic(false);
                }}
                onHiding={() => {
                    setVisibleLogic(false);
                }}
            >
                {() => {
                    return (
                        <span>{`模板名称“${templateName}”已存在,是否要覆盖？`}</span>
                    );
                }}
            </DevPopup.Logic>
            <LoadPanel
                visible={isShowGloablLoad}
                showIndicator={true}
                showPane={true}
            />
        </>

    )
});

export default SaveTemplate;